package gameobjects;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;


public class Entity {
	private int handle;
	private String name;
	private String spriteName;
	private int x;
	private int y;
	private int w;
	private int h;
	private String direction;
	
	public Entity() {
		this(-1,"",null,0,0,0,0);
		direction = "right";
	}
	
	public Entity(int h, String n, String s, int x, int y, int w, int he){
		handle = h;
		name = n;
		spriteName = s;
		this.x = x;
		this.y = y;
		this.w = w;
		this.h = he;
		direction = "right";
	}
	
	public void draw(Graphics graphics, Entity cam){
		if (spriteName != null){
			URL res = getClass().getResource("..\\sprites/" + spriteName + ".png");
	    	
			if (res != null){
				
			    try {
			    	BufferedImage  mirrorImg = ImageIO.read(res);
			    	AffineTransform tx = AffineTransform.getScaleInstance(-1, 1);
			        tx.translate(-mirrorImg.getWidth(null), 0);
			        AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
			        mirrorImg = op.filter(mirrorImg, null);
			    	
			    	
					if (this.direction == "right")
						graphics.drawImage(ImageIO.read(res), x - cam.getX(), 405-y-h, null);
			    	else if (this.direction == "left")
			    		graphics.drawImage(mirrorImg, x - cam.getX(), 405-y-h, null);
			    		
			    	
			    	
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public void move(int x, int y){
		this.x += x;
		this.y += y;
		
		// changing directions:
		if (this.direction == "right" && x < 0)
			direction = "left";
		else if ( this.direction == "left" && x > 0 )
			direction = "right";
		
	}
	
	public boolean doesCollide(Entity ent){
		Rectangle r1 = new Rectangle(x, y, w, h);
		Rectangle r2 = new Rectangle(ent.getX(), ent.getY(), ent.getW(), ent.getH());
		return r1.intersects(r2);
	}

	public int getHandle() {
		return handle;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSpriteName() {
		return spriteName;
	}

	public void setSpriteName(String spriteName) {
		this.spriteName = spriteName;
	}

	public int getX() {
		return x;
	}

	public void setX(int x) {
		this.x = x;
	}

	public int getY() {
		return y;
	}

	public void setY(int y) {
		this.y = y;
	}

	public int getW() {
		return w;
	}

	public void setW(int w) {
		this.w = w;
	}

	public int getH() {
		return h;
	}

	public void setH(int h) {
		this.h = h;
	}
	
	public String getDirection() {
		return direction;
	}
	
	public void setDirection(String direction) {
		this.direction = direction;
	}
}
